package utils

import (
	"bufio"
	"errors"
	"io"
	"os"
)

//	读取文件中的数据
func ReadJsonFileWithSearch(filePath string, searchDepth int) (result string, err error) {
	filePath1 := filePath
	exists := false
	for i := 0; i < searchDepth; i++ {
		if exists, _ = PathExists(filePath1); !exists {
			filePath1 = "../" + filePath1
			continue
		}
	}
	if exists {
		return ReadJsonFile(filePath1)
	} else {
		return "", errors.New("not existed")
	}
}

//	读取文件中的数据
func ReadJsonFile(filePath string) (result string, err error) {
	var file *os.File
	file, err = os.Open(filePath)
	defer file.Close()
	if err != nil {
		return
	}
	buf := bufio.NewReader(file)
	for {
		var s string
		s, err = buf.ReadString('\n')
		result += s
		if err != nil {
			if err == io.EOF {
				err = nil
				break
			} else {
				return
			}
		}
	}
	return
}
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
